package org.jdemo.util;

import com.sun.crypto.provider.SunJCE;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Date;

@SuppressWarnings("restriction")
public class EncryptUtil {
	private static final String ALGORITHM = "DES";
	private static final byte[] KEY = "MNSLEMOL".getBytes();

	static {
		Security.addProvider(new SunJCE());
	}
	
	public static String md5Encode(String s) {
		if(s != null) {
			MessageDigest messageDigest = null;
			try {
	            messageDigest = MessageDigest.getInstance("MD5");
	            messageDigest.reset();
	            messageDigest.update(s.getBytes("UTF-8"));
	        } catch (Exception e) {
	        	e.printStackTrace();
	        }
	        if(messageDigest != null) {
	        	byte[] byteArray = messageDigest.digest();
		        StringBuffer md5StrBuff = new StringBuffer();
		        for (int i = 0; i < byteArray.length; i++) {
		            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1){
		            	md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
		            }else {
		            	md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		            }
		        }
		        return md5StrBuff.toString();
	        }
		}
		return s;
	}
	
	/**
	 * BASE64加密
	 * @param input
	 * @return
	 */
	public static String base64Encode(String input) {
		if(input == null) {
			return null;
		}
		try {
			BASE64Encoder base64Encoder = new BASE64Encoder();
			return base64Encoder.encode(input.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}
	
	/**
	 * BASE64解密
	 * @param input
	 * @return
	 */
	public static String base64Decode(String input) {
		if(input == null) {
			return null;
		}
		BASE64Decoder base64Decoder = new BASE64Decoder();
		try {
			return new String(base64Decoder.decodeBuffer(input), "utf-8");
		} catch (IOException e) {
			return null;
		}
	}
	
	/**
	 * DES加密
	 * @param input
	 * @return
	 * @throws Exception
	 */
	public static String desEncode(String input) {
		try {
			SecretKey deskey = new SecretKeySpec(KEY, ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, deskey);
			byte[] cipherByte = cipher.doFinal(input.getBytes());
			
			return byte2hex(cipherByte);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * DES解密
	 * @param input
	 * @return
	 * @throws Exception
	 */
	public static String desDecode(String input) {
		try {
			SecretKey deskey = new SecretKeySpec(KEY, ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, deskey);
			byte[] clearByte = cipher.doFinal(hex2byte(input));
			return new String(clearByte);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * url的参数加密
	 * @param param
	 * @return
	 */
	public static String paramEncode(String param) {
		return base64Encode(desEncode(param));
	}
	
	/**
	 * url的参数解密
	 * @param param
	 * @return
	 */
	public static String paramDecode(String param) {
		return desDecode(base64Decode(param));
	}
	
	/**
	 * 十六进制转为字节码
	 * @param strhex
	 * @return
	 */
	private static byte[] hex2byte(String strhex) { 

        if (strhex == null) { 
            return null; 
        } 
        int l = strhex.length(); 

        if (l % 2 == 1) { 
            return null; 
        } 
        byte[] b = new byte[l / 2]; 
        for (int i = 0; i != l / 2; i++) { 
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16); 
        } 
        return b; 
    } 

	/**
	 * 字节码转为16进制
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) { 
        String hs = ""; 
        String stmp = ""; 
        for (int n = 0; n < b.length; n++) { 
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) { 
                hs = hs + "0" + stmp; 
            } else { 
                hs = hs + stmp; 
            } 
        } 
        return hs.toUpperCase(); 
    }

    private static char digits[] = "0123456789abcdefghijklmnopqrstuv".toCharArray();

    public static String encodeTimestamp(long i) {
        int shift = 5;
        char[] buf = new char[64];
        int charPos = 64;
        int radix = 1 << shift;
        long mask = radix - 1;
        do {
            buf[--charPos] = digits[(int)(i & mask)];
            i >>>= shift;
        } while (i != 0);
        return new String(buf, charPos, (64 - charPos));
    }

    public static String decodeTimestamp(String s) {
        return null;
    }

    public static void main(String[] args) {
        long time = new Date().getTime();
        System.out.println(time);
        System.out.println(encodeTimestamp(time));
        System.out.println(Long.parseLong(encodeTimestamp(time), 32));
    }
}
